package com.nrgedge.magnolia.form.components;

import info.magnolia.context.MgnlContext;
import info.magnolia.module.ModuleRegistry;
import info.magnolia.module.form.templates.components.FormFieldModel;
import info.magnolia.rendering.model.RenderingModel;
import info.magnolia.rendering.template.RenderableDefinition;
import info.magnolia.templating.functions.TemplatingFunctions;

import javax.jcr.Node;
import javax.servlet.http.HttpServletRequest;

import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaFactory;
import net.tanesha.recaptcha.ReCaptchaImpl;

import com.nrgedge.magnolia.ReCaptchaModule;

public class ReCaptchaModel<T extends RenderableDefinition> extends FormFieldModel<T> {

	public ReCaptchaModel(Node content, T definition, RenderingModel<?> parent, TemplatingFunctions functions) {
		super(content, definition, parent, functions);
	}

	public String getRecaptcha() {
		ReCaptchaModule module = (ReCaptchaModule) ModuleRegistry.Factory.getInstance().getModuleInstance("recaptcha");

		ReCaptcha c = ReCaptchaFactory.newReCaptcha(module.getPublicKey(), module.getPrivateKey(), false);
		
		HttpServletRequest request = MgnlContext.getWebContext().getRequest();
		
		if (request.isSecure()) {
			((ReCaptchaImpl)c).setRecaptchaServer("https://www.google.com/recaptcha/api");
		}
		
		return c.createRecaptchaHtml(null, null);
	}

}
